import { createUseStyles } from "react-jss";
import { ThemeContext } from "../../theme";
import Field from "../components/Field";
import React, { useContext } from "react";
import RenderComponent from "./render";
import type { FormItemProps } from "../type";

export default FormItem;

const useStyles = createUseStyles({
  note: {
    fontSize: (props: { fontSize: number }) => props.fontSize,
    color: "#333",
    border: "1px solid #d9d9d9",
    display: "inline-block",
    padding: "0 10px",
    lineHeight: "22px",
    borderColor: "#b3e2ff",
    borderRadius: "4px",
    backgroundColor: "#e6f7ff",
  },
});

function FormItem({
  field,
  isLast,
  index,
  justify,
  showError,
  labelWidth,
  isValid,
  errmsg,
  onChange,
}: FormItemProps) {
  const { label, required, labelTips } = field;

  const shownErrmsg = showError && !isValid ? errmsg : undefined;
  const { fontSize } = useContext(ThemeContext);
  const classes = useStyles({ fontSize });

  return (
    <>
      {field.note && <div className={classes.note}>{field.note}</div>}
      <Field
        slack
        isLast={isLast}
        labelWidth={labelWidth}
        labelTips={labelTips}
        label={label}
        required={required}
        errmsg={shownErrmsg}
        justifyContent={justify}
      >
        <RenderComponent
          index={index}
          field={field}
          isValid={showError ? isValid : true}
          showError={showError}
          onChange={onChange}
        />
      </Field>
    </>
  );
}
